﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Service
{
    public class AuthenticateUser:ICommand
    {
        
        DataLayer.DBFacade DB;
        Model.Account account;
        bool isAuthenticated;
        int pin;


        public bool IsAuthentecated { get { return isAuthenticated; } }

        public Model.Account CurrentAccount { get { return account; } }

        public AuthenticateUser(Model.Account account)
        {
            DB = new DataLayer.DBFacade();
            this.account = account;
            isAuthenticated = false;
        }

        public bool Execute()
        {
            string query = "SELECT *  FROM [dbo].[User] u inner join account a on u.userid=a.userid where pin="+account.PIN;
            DataTable dt = DB.Read(query);
            if (dt.Rows.Count>0)
            {
                try
                {
                    DataRow dr=dt.Rows[0];
                    account = new Model.Account();
                    account.User = new Model.User();
                    account.AccountNumber = Convert.ToDouble(dr["AccountNo"].ToString());
                    account.User.ID = Convert.ToInt32(dr["UserID"].ToString());
                    account.User.Name = dr["Name"].ToString();
                    account.ID = Convert.ToInt32(dr["id"].ToString());
                    account.PIN = Convert.ToInt32(dr["PIN"].ToString());
                    
                    isAuthenticated= true;
                }
                catch (Exception ex)
                {

                    isAuthenticated = false;
                }

                
            }
           
            return IsAuthentecated;
        }

        public bool Undo()
        {
            throw new NotImplementedException();
        }
    }
}